local UIBase = require("view.UIBase")
local HeroTrainView = class("HeroTrainView", UIBase)
local HeroDataHelper = require("data.helper.HeroDataHelper")
local TextHelper = require("utils.TextHelper")
local AttributeConst = require("const.AttributeConst")
local DataConst = require("const.DataConst")
local TypeHelper = require("utils.TypeHelper")
local UserDataHelper = require("data.helper.UserDataHelper")

local MAX_TAB = 2

local MAX_COST = 3

local ATTR_LIST = {
    AttributeConst.BLOOD,
    AttributeConst.ATTACK,
    AttributeConst.DEFENSE
}

function HeroTrainView:ctor(unit)
    self._unit = unit
    local resource = {
        path = "Prefabs/View/heroTrain",
        name = "HeroTrainView",
        canvas = 2
    }
    HeroTrainView.super.ctor(self, resource)
end

function HeroTrainView:start()
    self._signalEquipmentSuccess =
        G_SignalManager:add(SignalConst.EVENT_EQUIPMENT_ADD_SUCCESS, handler(self, self._onEventEquipmentSuccess))
    self._signalEquipClear =
        G_SignalManager:add(SignalConst.EVENT_EQUIPMENT_CLEAR_SUCCESS, handler(self, self._onEventEquipmentClear))
    self._signalMagicEquip =
        G_SignalManager:add(SignalConst.EVENT_MAGICKEY_EQUIP_SUCCESS, handler(self, self._onEventMagicEquip))
    self._signalMagicClear =
        G_SignalManager:add(SignalConst.EVENT_MAGICKEY_CLEAR_SUCCESS, handler(self, self._onEventMagicClear))

    self._btnClose.onClick:AddListener(handler(self, self._onBtnCloseClick))
    self._btnUnload.onClick:AddListener(handler(self, self._onBtnUnloadClick))
    self._btnChange.onClick:AddListener(handler(self, self._onBtnChangeClick))

    self._iconEquip:setCallback(handler(self, self._onIconEquipClick))
    self._iconMagic:setCallback(handler(self, self._onIconMagicClick))

    local config = self._unit:getConfig()
    self._textHeroName.text = config.name
    self._heroSpine:updateUI(self._unit:getBase_id())
    self._textDetail.text = config.desc
    self:_updateMagicKey()
    self:_updateEquip()
    self:_updateSkill()
    self:_updateLevel()
    self:_updateCost()
end

function HeroTrainView:onDestroy()
    self._signalEquipmentSuccess:remove()
    self._signalEquipmentSuccess = nil
    self._signalEquipClear:remove()
    self._signalEquipClear = nil
    self._signalMagicEquip:remove()
    self._signalMagicEquip = nil
    self._signalMagicClear:remove()
    self._signalMagicClear = nil
end

function HeroTrainView:_onEventEquipmentSuccess(id, message)
    self:_updateEquip()
end

function HeroTrainView:_onEventEquipmentClear()
    self:_updateEquip()
end

function HeroTrainView:_onEventMagicEquip()
    self:_updateMagicKey()
end

function HeroTrainView:_onEventMagicClear()
    self:_updateMagicKey()
end

function HeroTrainView:_updateSkill()
    local skillIds = self._unit:getSkills()
    for i = 1, 3 do
        if skillIds[i] then
            self["_skillIcon" .. i]:setVisible(true)
            self["_skillIcon" .. i]:updateUI(skillIds[i])
        else
            self["_skillIcon" .. i]:setVisible(false)
        end
    end
end

function HeroTrainView:_updateEquip()
    local equipUnit = G_UserData:getBattle():getBattleEquipment(self._unit:getPos())
    if equipUnit then
        self._iconEquip:updateUI(equipUnit:getType(), equipUnit:getBase_id())
    else
        self._iconEquip:updateEmpty()
    end
end

function HeroTrainView:_updateMagicKey()
    local magicId = self._unit:getMagickeyId()
    local magicUnit = G_UserData:getMagickey():getUnitById(magicId)
    if magicUnit then
        self._iconMagic:updateUI(magicUnit:getType(), magicUnit:getBase_id())
    else
        self._iconMagic:updateEmpty()
    end
end

function HeroTrainView:_onBtnUnloadClick()
    G_UserData:getBattle():clearHeroInBattle(self._unit:getId())
    G_UIManager:showTip(Lang.get("lang_hero_un_battle"))
    self:close()
end

function HeroTrainView:_onBtnChangeClick()
    local pop = require("view.hero.PopupChooseHero").new(handler(self, self.onSelectedHero))
end

function HeroTrainView:onSelectedHero(heroId)
    if heroId == 0 then
        return
    end
    G_UserData:getBattle():changeHeroToBattle(self._unit:getPos(), heroId)
    G_UIManager:showTip(Lang.get("lang_hero_change_success"))
    self:close()
end

function HeroTrainView:_updateCost()
    for i = 1, MAX_COST do
        local haveItem = UserDataHelper.getNumByTypeValue(TypeHelper.TYPE_ITEM, DataConst["ITEM_EXP_" .. i])
        self["_iconExp" .. i]:updateUI(TypeHelper.TYPE_ITEM, DataConst["ITEM_EXP_" .. i], haveItem)
        self["_iconExp" .. i]:showCount(true)
        self["_iconExp" .. i]:setCallback(
            function()
                self:_onIconExpClick(i)
            end
        )
    end
end

function HeroTrainView:_updateLevel()
    local attrs = HeroDataHelper.getHeroUnitAttr(self._unit)
    for i = 1, #ATTR_LIST do
        local name, value = TextHelper.getAttrBasicText(ATTR_LIST[i], attrs[ATTR_LIST[i]])
        self["_textAttrName" .. i].text = name .. ":"
        self["_textAttr" .. i].text = "+" .. value
    end
    local maxExp = HeroDataHelper.getHeroCurMaxExp(self._unit)
    local curExp = self._unit:getExp()
    self._textLevel.text = self._unit:getLevel()
    self._textExpProgress.text = curExp .. "/" .. maxExp
    self._imageExpBar.fillAmount = curExp / maxExp
end

function HeroTrainView:_onIconEquipClick()
    local pop = require("view.equipment.PopupEquipment").new(self._unit:getPos())
end

function HeroTrainView:_onIconExpClick(index)
    local haveItem = UserDataHelper.getNumByTypeValue(TypeHelper.TYPE_ITEM, DataConst["ITEM_EXP_" .. index])
    if haveItem > 0 then
        local itemCfg = require("config.items").get(DataConst["ITEM_EXP_" .. index])
        G_UserData:getItems():useItem(DataConst["ITEM_EXP_" .. index], 1)
        G_UserData:getHero():upgradeHero(self._unit:getId(), itemCfg.value)
        G_UIManager:showTip(Lang.get("lang_hero_add_exp", {exp = itemCfg.value}))
        self:_updateLevel()
        self:_updateCost()
    else
        local param = self["_iconExp" .. index]:getItemParam()
        local pop = require("view.popup.PopupItemTips").new(param)
    end
end

function HeroTrainView:_onIconMagicClick()
    local pop = require("view.magicKey.PopupMagicKey").new(self._unit)
end

function HeroTrainView:_onBtnHeroUp()
end

function HeroTrainView:_onBtnCloseClick()
    self:close()
end

return HeroTrainView
